package com.homework.im.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.security.token.SSOToken;
import com.homework.im.common.Constant;
import com.homework.im.common.Result;
import com.homework.im.service.ChatService;
import com.homework.im.vo.ImUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Controller
@RequestMapping("/hw-im")
public class InitDataController {

    @Autowired
    ChatService chatService;

    @GetMapping("")
    public String chat() {

        return "index";
    }

    @ResponseBody
    @GetMapping("/getMineAndGroupData")
    public Result getMineAndGroupData(HttpServletRequest request) {

        //从kisso里获取用户信息
        SSOToken ssoToken = SSOHelper.getSSOToken(request);
        ImUser user = chatService.getCurrentUserInfoFromKisso(ssoToken);

        //默认群
        Map<String, Object> group = new HashMap<>();
        group.put("name", "社区群聊");
        group.put("type", "group");
        group.put("avatar", "https://dwz.cn/c84QeOKg");
        group.put("id", Constant.DEFAULT_GROUP_ID);
        group.put("members", 0);

        return Result.ok(MapUtil.builder()
                .put("mine", user)
                .put("group", group)
                .map());
    }

    /**
     * 应该从通道里面获取所有用户信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getMembers")
    public Result getMembers() {

        Set<Object> members = chatService.findAllOnlineMembers();

        log.info("获取群成员---------->" + JSONUtil.toJsonStr(members));

        return Result.ok(MapUtil.of("list", members));
    }

    @ResponseBody
    @GetMapping("/getGroupHistoryMsg")
    public Result getGroupHistoryMsg() {

        List<Object> messages = chatService.getGroupHistoryMsg(20);
        return Result.ok(messages);
    }

}
